package org.jackysoft.report.rows;

import java.util.Collection;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.jackysoft.entity.MonthPlanItemType;
import org.jackysoft.entity.MonthPlanningItem;
import org.jackysoft.entity.Product;
import org.jackysoft.report.ProductValidation;
import org.jackysoft.service.ProductService;
import org.jackysoft.util.AbstractRowWatcher;
import org.jackysoft.util.ExcelUtil;

public class PlanningItemRowWatcher extends AbstractRowWatcher {
	
	private Log logger = LogFactory.getLog(PlanningItemRowWatcher.class);
	private ProductService _productService;
	
	private Collection<MonthPlanningItem> mpis = null;
	/**
	 * @param  mps 部门=>计划项集合
	 * @param  _productService 产品服务层
	 * */
	public PlanningItemRowWatcher(
			Collection<MonthPlanningItem> mpis,
			ProductService _productService
			) {
		super();
		this.mpis = mpis;
		this._productService = _productService;
	}

	@Override
	public void accept(Row row) {
		
	
		int lineNumber = row.getRowNum()+1;
		// format style
		// No, code name, unit, number, validate, remark;
		
			
	
		//代码名称
		Cell codeNameCell = row.getCell(0);
		String codeName = StringUtils.trimToEmpty(ExcelUtil.cellString(codeNameCell));
		
		if (StringUtils.isEmpty(codeName)) {
			logger.warn("no code name specified ,ignore this row ");
			return;
		}
		String[] cns = codeName.split("\\s+");
		
		if (cns == null || cns.length != 2) {
			appendError("代码名称列需要用空格隔开 " + codeName + " 行:%d", lineNumber);
			logger.warn(String.format("代码名称列需要用空格隔开 " + codeName + " 行:%d", lineNumber));			
		}
		String code = StringUtils.trimToEmpty(cns[0]);
		if(StringUtils.isEmpty(code)){
			appendError("代码名称不能为空 " + codeName + " 行:%d", lineNumber);
			logger.warn(String.format("代码名称不能为空 " + codeName + " 行:%d", lineNumber));			
		    return;
		}
		Product p = _productService.get(code);
		
		if (p == null) {
			appendError("代码为 %s 的产品没有找到,请到到产品管理调整  行: %d",code,lineNumber);
			logger.warn(String.format("代码为 %s 的产品没有找到,请到到产品管理调整  行: %d",code,lineNumber));
			return;
		}
		
		MonthPlanningItem mpi = new MonthPlanningItem();
		
		mpi.setOwner(p);
		
		//数量
		Cell nCell = row.getCell(2);
		Double value = ExcelUtil.cellNumber(nCell);
		mpi.setValue(value);

		
		// 解析校验列
		Cell vcell = row.getCell(3);
		ProductValidation vdr = null;
		String vString = ExcelUtil.cellString(vcell);
		if (StringUtils.isEmpty(vString)) {
			vdr = ProductValidation.无校验;
		} else {
			
			vdr = ProductValidation.valueOf(vString);
		}
		mpi.setValidator(vdr);
		// 备注
		Cell rCell = row.getCell(4);
		mpi.setRemark(ExcelUtil.cellString(rCell));
		//logger.info("\t"+mpi);
		mpi.setItemType(MonthPlanItemType.Proterozoic);
		mpis.add(mpi);

	}

}
